package com.ruoyi.workflow.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.impl.BpmnModelConstants;
import org.camunda.bpm.model.bpmn.instance.*;

import java.util.List;

/**
 * 多实例执行监听器-动态分配处理人（所有多实例用户任务自动设置）
 *
 * @author TD
 * @version 1.0
 * @date 2024/1/2
 */
@Slf4j
public class StartMultiInstanceLoopCharacteristicsExecutionListener implements ExecutionListener {

    public void notify(DelegateExecution delegateExecution) throws Exception {
        ExecutionEntity execution = (ExecutionEntity) delegateExecution;

        // 1. 获取多实例用户任务
        String activityId = execution.getActivityId(); // Activity_0cu8h13#multiInstanceBody
        String userTaskActivityId = StrUtil.removeSuffix(activityId, "#multiInstanceBody");
        BpmnModelInstance bpmnModelInstance = execution.getBpmnModelInstance(); // 当前模型对象
        UserTask userTask = bpmnModelInstance.getModelElementById(userTaskActivityId);

        // 2. 获取配置的多个用户
        String multipleUsers = userTask.getAttributeValueNs(BpmnModelConstants.CAMUNDA_NS, "multipleUsers"); //
        List<String> users = StrUtil.split(multipleUsers, StrUtil.C_COMMA);
        execution.setVariableLocal("assigneeList", users); // 设置审批集合

    }
}
